﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using Joel.Net;
using Umbraco.Forms.Data;
using Umbraco.Forms.Core.Services;
using Umbraco.Forms.Data.Storage;


namespace ContourStrikesAgain.WorkflowTypes
{
    public class AkismetCommentSpamProtection : WorkflowType
    {
        [Umbraco.Forms.Core.Attributes.Setting("Akismet API Key", 
            description = @"Don't have a key, signup <a href='https://akismet.com/signup/'>here</a>")]
        public string AkismetAPIKey { get; set; }

        [Umbraco.Forms.Core.Attributes.Setting("Field containing content",
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
        public string ContentField { get; set; }

         [Umbraco.Forms.Core.Attributes.Setting("Field containing author name",
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
        public string AuthorField { get; set; }

         [Umbraco.Forms.Core.Attributes.Setting("Field containing author email",
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
        public string AuthorEmailField { get; set; }

         [Umbraco.Forms.Core.Attributes.Setting("Field containing author website",
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
        public string AuthorUrlField { get; set; }

         [Umbraco.Forms.Core.Attributes.Setting("Field to store spam status",
            control = "Umbraco.Forms.Core.FieldSetting.FieldPicker")]
         public string SpamField { get; set; }

        public AkismetCommentSpamProtection()
        {
            this.Name = "Akismet spam protection";
            this.Id = ProviderIDCollection.akismetCommentSpamProtectionProviderGuid;
            this.Description = "Add smap protection";

            
        }

        public override List<Exception> ValidateSettings()
        {
            List<Exception> exceptions = new List<Exception>();

            if(string.IsNullOrEmpty(AkismetAPIKey))
                exceptions.Add(new Exception("Please provide an Akismet API Key"));

            return exceptions;
        }

        public override Umbraco.Forms.Core.Enums.WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {

            try
            {
                var api = new Akismet(
                       AkismetAPIKey,
                       "http://" + HttpContext.Current.Request.ServerVariables["HTTP_HOST"],
                       "Umbraco Contour");

                var comment = new AkismetComment
                {
                    UserAgent = HttpContext.Current.Request.UserAgent,
                    UserIp = record.IP,
                    CommentType = "comment",
                    CommentAuthor = GetFieldValue(record, AuthorField),
                    CommentAuthorEmail = GetFieldValue(record, AuthorEmailField),
                    CommentAuthorUrl = GetFieldValue(record, AuthorUrlField),
                    CommentContent = GetFieldValue(record, ContentField)
                };

                bool isSpam = api.CommentCheck(comment);

                var spamFld = record.RecordFields.Values.Where(x => x.Field.Id == new Guid(SpamField)).FirstOrDefault();

                if (spamFld != null)
                {
                    spamFld.Values.Clear();
                    spamFld.Values.Add(isSpam);

                    FormStorage fs = new FormStorage();
                    Form f = fs.GetForm(record.Form);
                    RecordStorage rs = new RecordStorage();
                    rs.UpdateRecord(record, f);
                    rs.UpdateRecordXml(record, f);

                    fs.Dispose();
                    rs.Dispose();
                }


                return Umbraco.Forms.Core.Enums.WorkflowExecutionStatus.Completed;
            }
            catch (Exception ex)
            {
                LogHelper.Error("Spam check failed: " + ex.Message);
                return Umbraco.Forms.Core.Enums.WorkflowExecutionStatus.Failed;
            }
        }

        private string GetFieldValue(Record record, string fieldGuid)
        {
           
            if (record.RecordFields.Values.Where(x => x.Field.Id == new Guid(fieldGuid)).FirstOrDefault() != null)
                return record.RecordFields.Values.Where(x => x.Field.Id == new Guid(fieldGuid)).FirstOrDefault().ValuesAsString();
            else
                 return string.Empty;
           
            
        }
    }
}